#include "MemoryPool.hpp"

/** 
* Initializes an empty 0 byte pool.
*/
MemoryPool::MemoryPool(){
	location = 0;
	lastLocation = 0;
	size = 0;
}

/** 
* Create memory pool of size s bytes.
* @param s Size of pool in bytes.
*/
void MemoryPool::createPool(unsigned int s){
	size = s;
	pool = new byte[size];
    clear();
}

/** 
* Allocates as bytes in the pool.
* @parama s Number of bytes to allocate.
* @return Pointer to beginning of allocated memory, or 0 if failed.
*/
void* MemoryPool::allocate(size_t as){
	//Check if we have enough space for this allocation.
	if(location + as >= size){
		return 0;
	}
	
	lastLocation = location;
	location += as;
	return (pool + (lastLocation));
}

/**
 * Copy data of size as to pool.
 * @param as Size in bytes.
 * @param data Data to copy.
 * @return true if copy succeeded, false otherwise.
 */
bool MemoryPool::copy(size_t as, void* data) {
	void* allocatedLocation = allocate(as);
    if (!allocatedLocation){
	    return false;
	}
	memcpy(allocatedLocation, data, as);
    return true;
}

/** 
* Clears the pool by resetting position to 0.
*/
void MemoryPool::clear(){
	location = 0;
	lastLocation = 0;
}


/** 
* Clears memory pool buffer from memory.
*/
MemoryPool::~MemoryPool(){
	if(size != 0){
		delete pool;
		size = 0;
		pool = 0;
	}
}